var express = require('express');
var router = express.Router();

var md5 = require('md5');
var fs = require('fs');
var conn = require("../setting");

/* GET users listing. */
router.get('/login', function(req, res, next) {
	res.render("login",{title:"登陆页面"})
});

router.post('/dologin',function(req,res,next){
	var username = req.body.username;
	
	var password = md5(req.body.password);
	var sql = 'select * from users where username="'+req.body.username+'" and password ="'+password+'"';
	conn.query(sql,function(err,rows,fields){
		console.log(rows)
		if (rows.length!=0) {

			req.session.is_login = true;
			req.session.user_name = username;
			console.log('哈哈哈哈哈哈吼吼'+req.session.user_name)
			/*var cookie_id = Math.floor(1000*Math.random());			
			fs.appendFileSync(''+cookie_id,"获取cookie，可以登录")
			res.cookie("cookie_id",cookie_id)*/
			res.send('登陆成功')
		}else{
			res.send('用户名或密码不正确')
		}
	})

	/*if (req.body.username=='admin' && req.body.password=="123") {
		res.cookie("islogin","true")
		res.redirect('/admin/articleLists')
	}else{
		res.send("重新登陆")
	}*/
	
})

router.get('/register', function(req, res, next) {
	res.render("register",{title:"注册页面"})
});

router.post('/register',function(req,res,next){
	var password = md5(req.body.password);
	var sql = 'insert into users values(null,"'+req.body.username+'","'+password+'")';
	conn.query(sql,function(err,rows,fields){
		res.redirect('login')
		})
	})

module.exports = router;
